package vn.candyapp.qlct.adapter;

import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Date;
import java.util.List;
import vn.candyapp.qlct.R;
import vn.candyapp.qlct.database.DBAdapter;
import vn.candyapp.qlct.database.model.Transaction;
import vn.candyapp.qlct.item.KieuTKGiaoDich;
import android.content.Context;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class DsGiaoDichAdapter extends BaseAdapter {

	private LayoutInflater mInflater;
	private List<Transaction> mData;
	private DBAdapter dbAdapter;
	private Handler mHandler;
	
	public DsGiaoDichAdapter(Context context) {
		mInflater = LayoutInflater.from(context);
		dbAdapter = new DBAdapter(context);
		mHandler = new Handler();
	}
	
	public void loadData(final Runnable run, final Date date, final KieuTKGiaoDich dType) {
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				mData = dbAdapter.getAllTransaction(date, dType);
				mHandler.post(run);
			}
		}).start();
	}
	
	@Override
	public int getCount() {
		return mData.size();
	}

	@Override
	public Object getItem(int position) {
		return mData.get(position);
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder = null;
		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.simple_list_item, parent, false);
			holder = new ViewHolder();
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		holder.tvAmount = (TextView) convertView.findViewById(R.id.tvAmount);
		holder.tvReason = (TextView) convertView.findViewById(R.id.tvReason);
		holder.tvDatetime = (TextView) convertView.findViewById(R.id.tvDatetime);
		holder.tvAccount = (TextView) convertView.findViewById(R.id.tvTaiKhoan);
		
		Transaction tran = (Transaction) getItem(position);
		int balanceValue = Float.valueOf(tran.getAmount()).intValue();
		if (tran.getTransactionTypeName().equals("expense")) 
			balanceValue = -balanceValue;
		holder.tvAmount.setText(int2CurrencyStr(balanceValue));
		holder.tvDatetime.setText(tran.getCreatedDate());
		holder.tvReason.setText(tran.getCategoryName());
		holder.tvAccount.setText(tran.getAccountName());
		return convertView;
	}
	
	public String int2CurrencyStr(int value) {
		DecimalFormat df = new DecimalFormat();
		DecimalFormatSymbols dfs = new DecimalFormatSymbols();
		dfs.setGroupingSeparator('.');
		df.setGroupingSize(3);
		df.setGroupingUsed(true);
		df.setDecimalFormatSymbols(dfs);
		return df.format(value);

	}
	
	private class ViewHolder {
		public TextView tvAmount, tvDatetime, tvReason, tvAccount;
	}

}
